package cn.kent.simple;


/**
 * 206. 反转链表
 */
public class ReverseList {

    public static void main(String[] args) {
        ListNode node0 = new ListNode(0);
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(4);
        node0.next = node1;
        node1.next = node2;
        node2.next = node3;

        ListNode resNode = reverseList2(node0);

        System.out.println("result foreach:");
        while (resNode != null) {
            System.out.println(resNode.val);
            resNode = resNode.next;
        }
        System.out.println("==============");
    }

    /**
     * 递归
     */
    public static ListNode reverseList2(ListNode head) {
        if (head == null || head.next == null) {
            return head;
        }
        ListNode newHead = reverseList(head.next);
        head.next.next = head;
        head.next = null;
        return newHead;
    }

    /**
     * 0ms 100%
     * 迭代
     */
    public static ListNode reverseList(ListNode head) {
        ListNode next = null;
        while (head != null) {
            next = new ListNode(head.val, next);
            head = head.next;
        }
        return next;
    }

    static class ListNode {
        public int val;
        public ListNode next;

        public ListNode() {
        }

        public ListNode(int val) {
            this.val = val;
        }

        public ListNode(int val, ListNode next) {
            this.val = val;
            this.next = next;
        }
    }
}
